package com.taxinfo.controller;

import com.taxinfo.common.core.controller.BaseController;
import com.taxinfo.common.core.domain.AjaxResult;
import com.taxinfo.common.utils.IdUtils;
import com.taxinfo.common.utils.MD5Utils;
import com.taxinfo.manager.domain.Fileinfo;
import com.taxinfo.manager.domain.Paramer;
import com.taxinfo.manager.domain.Systemupdate;
import com.taxinfo.manager.service.IFileinfoService;
import com.taxinfo.manager.service.IParamerService;
import com.taxinfo.manager.service.ISystemupdateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 上传管理Controller
 *
 * @author ycong
 * @date 2023-12-24
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController extends BaseController {
    @Autowired
    private IFileinfoService fileinfoService;

    @Autowired
    private IParamerService paramerService;

    @Autowired
    private ISystemupdateService systemupdateService;

    @RequestMapping({"/upload"})
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        List<Paramer> paramers = paramerService.selectParamerList(new Paramer());
        if (CollectionUtils.isEmpty(paramers)){
            return AjaxResult.error("系统IP未配置！");
        }
        String IP = paramers.get(0).getIp();
        String md5 = MD5Utils.getMd5(file);
        if (file.isEmpty()) {
            return AjaxResult.error("文件为空");
        } else {
            String fileName = file.getOriginalFilename();
            logger.info("上传的文件名为：" + fileName);
            Fileinfo fileInfo = new Fileinfo();
            Systemupdate systemUpdate = new Systemupdate();
            fileInfo.setMd5(md5);
            systemUpdate.setVersion(fileName.substring(0, fileName.indexOf(".")));
            fileInfo.setFilename(fileName);
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            logger.info("上传的后缀名为：" + suffixName);
            String filePath = System.getProperty("user.dir") + "//imgs//";
            fileName = fileName.substring(0, fileName.indexOf("."));
            fileName = MD5Utils.createMd5(fileName) + suffixName;
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            try {
                file.transferTo(dest);
                fileInfo.setFilepath(fileName);
                fileInfo.setFiletype(suffixName);
                fileInfo.setFilepath("http://" + IP + ":" + "8383" + "/file/download?fileName=" + fileName);
                fileInfo.setUuid(IdUtils.uuid());
                if (!suffixName.contains("apk")) {
                    this.fileinfoService.insertFileinfo(fileInfo);
                } else {
                    this.systemupdateService.deleteAll();
                    systemUpdate.setUuid(IdUtils.uuid());
                    systemUpdate.setUrl("http://" + IP + ":" + "8383" + "/file/download?fileName=" + fileName);
                    this.systemupdateService.insertSystemupdate(systemUpdate);
                }
                return AjaxResult.success();
            } catch (IllegalStateException e) {
                log.error("文件上传报错，IllegalStateException，" + e.getMessage() );
            } catch (IOException e) {
                log.error("文件上传报错，IOException，" + e.getMessage() );
            }
        }

        return AjaxResult.success();
    }


    @RequestMapping({"/download"})
    public String downloadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileName) throws Exception {
        if (fileName != null) {
            String realPath = System.getProperty("user.dir") + "//imgs";
            File file = new File(realPath, fileName);
            if (!file.exists()) {
                return null;
            }

            response.setContentType("application/octet-stream");
            response.setContentLength((int)file.length());
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;

            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();

                for(int i = bis.read(buffer); i != -1; i = bis.read(buffer)) {
                    os.write(buffer, 0, i);
                }
            } catch (Exception e) {
                log.error("文件下载报错，Exception，" + e.getMessage() );
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        log.error("文件下载报错，IOException，" + e.getMessage() );
                    }
                }

                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        log.error("文件下载报错，IOException fis ，" + e.getMessage() );
                    }
                }

            }
        }

        return null;
    }
}
